using Agron.Data.Contracts;
using Agron.Services.SessionController;

using ComponentFactory.Krypton.Toolkit;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;


namespace Agron.UI.SmartClient
{
    partial class SessionModeForm : KryptonForm, IMemberListController
    {
        private const int TopMargin = 30;

        private IEnumerable<SessionMember> _sessionMemberArgument;

        /// <summary>
        /// Initializes a new instance of the <see cref="SessionModeForm"/> class.
        /// </summary>
        public SessionModeForm()
        {
            this.InitializeComponent();
            this.PositionForm();
            this.SetAnonymousMethods();
        }

        /// <summary>
        /// Handles the Load event of the SessionModeForm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SessionModeForm_Load(object sender, EventArgs e)
        {
            this.subjectLabel.Text = SessionManager.Instance.CurrentSession.Subject;
            this.descriptionTextBox.Text = SessionManager.Instance.CurrentSession.Description;
            this.infoKryptonHeaderGroup.ValuesSecondary.Heading = SessionManager.Instance.CurrentSession.SessionId.ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Attaches anonymous methods to some of the menus.
        /// </summary>
        private void SetAnonymousMethods()
        {
            this.editContactInfoToolStripMenuItem.Click += delegate { this.ProcessModalDialog<EditUserInfoForm>(); };
            this.hideToolbarToolStripMenuItem.Click += delegate { this.Close(); };
            this.helpToolStripButton.Click += delegate { Process.Start(string.Format(CultureInfo.InvariantCulture, "{0}/Forms/Faq.aspx", Properties.Settings.Default.WebsiteUrl)); };
            this.emailKryptonLinkLabel.LinkClicked += delegate { Process.Start(GetInvitationText(Properties.Resources.SessionModeFormEmailInvitationText)); };
            this.clipboardKryptonLinkLabel.LinkClicked += delegate { Clipboard.SetText(GetInvitationText(Properties.Resources.SessionModeFormClipboardInvitationText)); };
        }

        /// <summary>
        /// Displays a modal dialog by instantianting a new instance of the specified <typeparamref name="TDialog"/>/
        /// </summary>
        /// <typeparam name="TDialog">A dialog that implements <see cref="DialogBase"/>.</typeparam>
        internal void ProcessModalDialog<TDialog>() where TDialog : DialogBase, new()
        {
            using (TDialog dialog = new TDialog())
            {
                dialog.ShowDialog(this);
            }
        }

        /// <summary>
        /// Positions the <see cref="SessionModeForm"/> either by using the last know position or by positioning the form on the top right of the <see cref="Screen.PrimaryScreen"/>.
        /// </summary>
        private void PositionForm()
        {
            Screen primaryScreen = Screen.PrimaryScreen;

            base.Top = primaryScreen.WorkingArea.Top + SessionModeForm.TopMargin;
            base.Left = primaryScreen.WorkingArea.Width - base.Width;
        }

        /// <summary>
        /// Gets an overridden version of the CreateParams property that contains the required creation parameters for when the control handle is created.
        /// </summary>
        /// <value>
        /// An overriden version of the <see cref="CreateParams"/> property that contains the required creation parameters for when the control handle is created.
        /// </value>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams parameters = base.CreateParams;

                if (MainForm.IsWindowsXpOrAbove)
                    parameters.ClassStyle = (parameters.ClassStyle | Constants.CS_DROPSHADOW);

                return parameters;
            }
        }

        /// <summary>
        /// Handles the CellPainting event of the membersDataGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.DataGridViewCellPaintingEventArgs"/> instance containing the event data.</param>
        private void membersDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (0 == e.ColumnIndex)
            {
                e.PaintBackground(e.CellBounds, true);

                if (-1 == e.RowIndex)
                {
                    // Draw header image
                    DataGridViewUtils.DrawBitmapInCell(Properties.Resources.ContactsHeaderIcon, e);
                }
                else
                {
                    SessionMember sessionMember = (this.membersBindingSource[e.RowIndex] as SessionMember);
                    if (null != sessionMember)
                    {
                        if (!sessionMember.IsOnline)
                        {
                            DataGridViewUtils.DrawBitmapInCell(Properties.Resources.UserOfflineIcon, e);
                        }
                        else if (sessionMember.IsSessionOwner)
                        {
                            DataGridViewUtils.DrawBitmapInCell(Properties.Resources.UserOrganizerIcon, e);
                        }
                        else
                        {
                            DataGridViewUtils.DrawBitmapInCell(Properties.Resources.UserOnlineIcon, e);
                        }
                    }
                }

                e.Handled = true;
            }
            else if (1 == e.ColumnIndex)
            {
                e.PaintBackground(e.CellBounds, true);

                if (-1 == e.RowIndex)
                {
                    // Draw header image
                    DataGridViewUtils.DrawBitmapInCell(Properties.Resources.ColorPaletteHeaderIcon, e);
                }

                e.Handled = true;
            }
        }

        #region IMemberListController Members

        /// <summary>
        /// Performs data-binding processes based on the specified <see cref="IEnumerable{SessionMember}"/> collection.
        /// </summary>
        /// <param name="dataSource">The <see cref="IEnumerable{SessionMember}"/> collection to use a data source.</param>
        public void DataBind(IEnumerable<SessionMember> dataSource)
        {
            this._sessionMemberArgument = dataSource;

            if (base.InvokeRequired)
            {
                base.Invoke(new MethodInvoker(this.DataBindInternal));
            }
            else
            {
                this.DataBindInternal();
            }
        }

        #endregion

        private void DataBindInternal()
        {
            this.membersDataGridView.Enabled = false;
            this.membersBindingSource.DataSource = this._sessionMemberArgument;
            this.membersDataGridView.Enabled = true;
        }

        /// <summary>
        /// Handles the Click event of the stopToolStripButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void stopToolStripButton_Click(object sender, EventArgs e)
        {
            BrokerProgressForm.StopSession(this);
        }

        private static string GetInvitationText(string format)
        {
            return string.Format(CultureInfo.CurrentCulture, format,
                SessionManager.Instance.CurrentSession.Subject, 
                Properties.Settings.Default.WebsiteUrl,
                SessionManager.Instance.CurrentSession.SessionId);
        }
    }
}